/*
 * @Author: 曹捷
 * @Date: 2020-06-09 13:20:10
 * @LastEditors: 曹捷
 * @LastEditTime: 2021-06-21 16:05:59
 * @Description: 统一处理用户登录拦截，登录成功重定向等业务
 */
import store from "@/store";
import http from "@/config";
import config from "@/config/config";
import app from './app'
import { setPushAlias, removePush } from "./appPlug/jvPush";
/**
 * 拦截跳转登录  缓存当前页面和参数
 * @param {*function} callback
 */
export function toLogin (callback, redirect = '') {
  console.log("toLogin -> config", config);
  //?redirect=${redirect}
  uni.redirectTo({
    url: config.loginBaseUrl,
  });
  callback && callback();
}
/**
 * 登录成功 重定向到之前拦截登录的页面
 */
export function loginSuccess (params) {
  let key = params.type === 1 ? "toLogin" : "userLoginByMobile";
  this.$http[key](params).then((res) => {
    console.log('loginSuccess -> res', res)
    uni.setStorageSync("userInfo", res);
    this.$store.commit("setLogin", res);
    setPushAlias();
    let param = uni.getStorageSync("pager");
    let pages = getCurrentPages();
    if (param.url && param.url.indexOf("login") === -1 && pages.length > 1) {
      console.log('loginSuccess -> app', app)
      let url = param.url
      delete param.url
      app.goto(url, param)
    } else {
      app.goto(config.homeBaseUrl)
    }
  });
}
/**
 * 登录成功  路径回转
 */
export function loginBack () {
  let param = uni.getStorageSync("pager");
  console.log('🚀 ~ file: user.js ~ line 51 ~ loginBack ~ param', param)
  let pages = getCurrentPages();
  if (param.url && param.url.indexOf("login") === -1 && param.url.indexOf("register") === -1) {
    console.log('🚀 ~ file: user.js ~ line 53 ~ loginBack ~ param', param)
    let url = param.url
    console.log('🚀 ~ file: user.js ~ line 55 ~ loginBack ~ url', url)
    delete param.url
    app.redirectTo(url, param)
  } else {
    app.redirectTo(config.homeBaseUrl)
  }
}
/**
 * 修改个人用户信息，同步修改store和本地缓存
 * @param {*} res
 * 用户信息
 */
export function saveUserInfo (res) {
  let userinfo = uni.getStorageSync("userInfo");
  let newInfo = Object.assign(userinfo, res);
  uni.setStorageSync("userInfo", newInfo);
  this.$store.commit("setLogin", newInfo);
}
/**
 * 退出登录
 */
export function loginOut () {
  let user = uni.getStorageSync("userInfo");
  http.userLogout(user).then((res) => {
    uni.removeStorageSync("userInfo");
    removePush()
    store.commit("setLogin", {});
    uni.reLaunch({
      url: "/app-modules/pages/login/login",
    });
  });
}
/**
 * 没有登录页面拦截
 */
export function loginIntercept (url) {
  let user = store.state.login.userInfo
  if (user && (user.id || user.id === 0)) {
    return user
  } else {
    toLogin(url)
  }
}
